<?php
require_once 'utils/Log.php';
include('utils/Requests.php');
include('utils/Cache.php');
/**
 * Created by PhpStorm.
 * User: zpr
 * Date: 2017/6/20
 * Time: 16:54
 * 请求客户端
 */

class DefaultOpenApiClient{
    public $cache;
    function __construct() {
        $this->cache = new Cache();
        $this->appid = "10037e6f6a4e6da4016a62a47e51000c";
        $this->appkey = "b4b70d123a724972bc21f445b0b9f75c";
    }
    /**
     * @param $request
     * @return type|void
     */
    public function execute($request,$appId,$appKey){
        try{
            Log::outLog($request->apiMethodName,"开始请求");
            Requests::register_autoloader();
            $url = $request->url.'/'.$request->apiVersion.$request->serviceCode;
            Log::outLog($request->apiMethodName,$url);
            $header = array('Content-Type'=>'application/json');
            if($request->needToken){
                if($this->cache->getCache("token")==false){
                    $token = self::getToken($appId,$appKey,$request->url);
                    $this->cache->setCache("token",$token);
                }else{
                    $token = $this->cache->getCache("token");
                }
                $header = array('Content-Type'=>'application/json',"Authorization"=>'OPEN-ACCESS-TOKEN AccessToken='.$token);
            }
            $data = $request->data;
            if($request->needDataTag){
                $data = '{"data":'.$request->data.'}';
            }
            Log::outLog($request->apiMethodName.'请求报文',$data);
            $content = Requests::post($url,$header,$data);
            Log::outLog($request->apiMethodName.'响应报文',$content->body);
            Log::outLog($request->apiMethodName,"请求结束");
            return $content->body;
        }catch (Exception $e){
            print_r('错误--'.$e);
            Log::outLog("发起请求exception:",$e);
        }
    }
    public function executeGet($appid,$appkey,$url,$data)
    {
        Requests::register_autoloader();
        $token = $this->getToken($appid,$appkey);
        $post_data = [
            "Authorization"=>'OPEN-FORM-PARAM',
            "appId" => $appid,
            "timestamp" => date('YmdHis'),
            "nonce" => date('YmdHis'),
            "content" => $data,
            "signature" => $token
        ];
        $url = $url.'?'.http_build_query($post_data);
        $header = array('Content-Type'=>'application/json',"Authorization"=>'OPEN-ACCESS-TOKEN AccessToken='.$token.',AppId='.$appid);
        Log::outLog('pay请求报文',$post_data);
        $content = Requests::get($url,$header);
        Log::outLog('pay',$content->body);
        Log::outLog('pay',"请求结束");
        dump($content->body);
        echo $content->body;
        return $content->body;
    }
    public static function getToken($appId,$appKey){
        Log::outLog('getToken','开始获取toekn');
        $url  = "https://test-api-open.chinaums.com/v2/token/access";
        $nonce = Tools::create_uuid();
        $timestamp = date("YmdHis",time());
        $timestamp = '20240508115116';
        $nonce = 'a20b22bc088742f7ccc3b111b07096a2';
        $str = $appId.$timestamp.$nonce.$appKey;
        $data = json_encode(array(
            'appId'=>$appId,
            'nonce'=>$nonce,
            'signature'=>sha1($str),
            'timestamp'=>$timestamp,
//            'signMethod' => 'SHA256',
        ));

        Log::outLog('token请求报文',$data);
        $response = Requests::post($url, array(
            'Content-Type'=>'application/json'
        ),$data);
        $jsonMap = json_decode($response->body,true);

        foreach($jsonMap as $key => $value){
            if($key=='accessToken'){
                Log::outLog('获取token成功',$value);
                return $value;
            }
        }
        return '获取token失败';
    }
    function SHA256Hex($str){
        $re=hash('sha256', $str, true);
        return bin2hex($re);
    }

    function getMerOrderId($msgSrcId){
        $billNo=$msgSrcId.date("YmdHis",time()).str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
        return $billNo;
    }
    function getSignature($timestamp,$nonce,$body){
        $str = bin2hex(hash('sha256', $body, true));
        dump('签名内容：'.$body);
        dump('SHA256(签名内容)：'.$str);
        dump('appId+ Timestamp + Nonce + SHA256(签名内容)：'."$this->appid$timestamp$nonce$str");
        dump('HmacSHA256(appId+ Timestamp + Nonce + SHA256(签名内容),appKey)：'.bin2hex(hash_hmac('sha256', "$this->appid$timestamp$nonce$str", $this->appkey, true)));
        $signature = base64_encode(hash_hmac('sha256', "$this->appid$timestamp$nonce$str", $this->appkey, true));
        dump('signature：'.$signature);
        return $signature;
    }
    function curlget($url,$body){
        Requests::register_autoloader();
        $timestamp= date("YmdHis",time());
        dump('timestamp：'.$timestamp);
        $nonce = md5(uniqid(microtime(true),true));
        dump('nonce：'.$nonce);
//        $timestamp = '20240508143612';
//        $nonce = '20240508143612';
//        $token = $this->getToken($this->appid,$this->appkey);
        $signature=$this->getSignature($timestamp,$nonce,$body);
//        dump($signature);
//        dump(base64_encode($signature));
        //authorization=OPEN-FORM-PARAM" + "&appId=" + appId + "&timestamp=" + timestamp + "&nonce=" + nonce;
        $reqUrl=$url."?authorization=OPEN-FORM-PARAM&appId=".$this->appid.'&'."timestamp=".$timestamp."&nonce=".
            $nonce."&content=".urlencode($body)."&signature=".$signature;
        dump('请求链接：'.$reqUrl);
//        $header = array('Content-Type'=>'application/json',"Authorization"=>'OPEN-ACCESS-TOKEN AccessToken='.$token.',AppId='.$this->appid);
        $header = array("Authorization"=>'OPEN-BODY-SIG AppId="'.$this->appid.'",Timestamp="'.$timestamp.'",Nonce="'.$nonce.'",Signature="'.$signature.'"');

        $content = Requests::get($reqUrl,$header);
        dump('请求结果：'.$content->body);
        return $reqUrl;

    }

    function curlpost($url,$body){
        $timestamp = date("YmdHis",time());
        $nonce = md5(uniqid(microtime(true),true));
        $signature = $this->getSignature($timestamp,$nonce,$body);
        $authorization = "OPEN-BODY-SIG AppId=\"$this->appid\", Timestamp=\"$timestamp\", Nonce=\"$nonce\", Signature=\"$signature\"";
        $ch = curl_init();//初始化curl

        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($body),
            'Authorization: '.$authorization
        ));
        $output = curl_exec($ch);//运行curl
        echo "响应报文：".$output."\r\n";
        curl_close($ch);
        return $output;

    }
}
